Skip to content

refactor: buffer database access - #398

Merged
Sekhmet merged 4 commits into
masterfrom
sekhmet/buffered-writes
Jul 31, 2026
Merged

Sekhmet merged 4 commits into
masterfrom
sekhmet/buffered-writes

Conversation

@Sekhmet

@Sekhmet Sekhmet commented Jul 28, 2026

Copy link
Copy Markdown
Member

To improve performance CRUD actions on database are now buffered. This reduces number of database round trips within writers.

Due to the internal structure of our entries (for time-travel queries and reorg handling) this is quite convoluted to keep track of this as we need to keep track of current and old versions of entities.

Entries are periodically flushed to database when reaching maximum number of pending rows or on time interval (to prevent failures from reverting too much work).

Once at the tip database is flushed in each block.

To improve performance CRUD actions on database are now buffered.
This reduces number of database round trips within writers.

Due to the internal structure of our entries (for time-travel queries
and reorg handling) this is quite convoluted to keep track of this as we
need to keep track of current and old versions of entities.

Entries are periodically flushed to database when reaching maximum
number of pending rows or on time interval (to prevent failures from
reverting too much work).

Once at the tip database is flushed in each block.
@Sekhmet
Sekhmet requested a review from bonustrack July 28, 2026 15:37

@tony8713 tony8713 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Approving.

Given this is the indexer behind Snapshot X, I didn't want to review the SQL by reading it, so I stood the branch up against a local Postgres 16 and drove a real Container through scripted workloads — including killing the process mid-buffer and injecting flush failures. Everything on the durability list checks out, and the branch fixes two real bugs that exist on master today. All findings below are non-blocking.


The important part: it cannot advance the cursor past lost writes

This was my main worry — buffering is exactly the change that can produce "cursor moved, rows never landed, no error". It can't here, for two structural reasons, and I confirmed both:

  1. last_indexed_block is buffered like everything else and emitted as the last statement of the same knex.transaction in flush(), so data and cursor commit or roll back together.
  2. flushBuffer() retries forever and never advances on failure.

Permanent flush failure (a writer emits a 400-char value for a varchar(256) column at block 20, so every attempt fails):

[flush error]  ... - value too long for type character varying(256)
[t+4s]  votes=0 max_count=-1 last_indexed_block=0 _blocks=0 flushErrors=2
[t+8s]  votes=0 max_count=-1 last_indexed_block=0 _blocks=0 flushErrors=4
[FINAL] votes=0 max_count=-1 last_indexed_block=0 _blocks=0 flushErrors=8

Error surfaced, cursor pinned at 0. Correct — it wedges loudly instead of skipping blocks.

Transient flush failure (a BEFORE INSERT trigger raises once, then is dropped):

[harness] flush error #1 / #2: sabotage: injected flush failure
[harness] sabotage trigger removed
[FINAL] votes=3126 last_indexed_block=3127 flushErrors=2

total_rows | distinct_ids | mn |  mx
      3128 |         3128 |  1 | 3128
duplicates: 0 rows

The buffer survives a failed flush intact and replays it exactly once — no gaps, no duplicates.

Crash / SIGTERM / SIGKILL / unhandled rejection, fired at block 25 with an un-flushed buffer — all four modes:

votes=0   last_indexed_block=0   blocks=0

Writes are lost, but the cursor is lost with them, so restart replays. Verified end to end: SIGKILL at block 7000 after a real flush at 5000 left votes=5000, last_indexed_block=5000; restarting and running on gave

total=10000  distinct_ids=10000  missing_in_1_10000=0  dupes=0
overlapping_ranges=0  last_indexed_block=10000

Replay is complete and idempotent.

Ordering

Correct. prepareFlush emits every close before every insert, and the GiST exclusion constraint on (id, _indexer, block_range) would reject any mistake, so this is enforced rather than assumed. I ran a window mixing rows that already existed in the DB with rows created inside the window, plus deletes and a re-create:

e1 count=1 range=[1,6)    e1 count=2 range=[6,8)    e1 count=3 range=[8,)
e2 count=1 range=[1,9)    e2 count=9 range=[12,)          <- deleted b9, recreated b12
e3 count=1 range=[1,10)                                   <- updated then deleted in b10
e4 count=1 range=[7,8)    e4 count=2 range=[8,11)         <- created b7, deleted b11
overlapping_ranges=0

I also ran the same 40-block workload three ways — master, this branch fully buffered (one flush at the end), and this branch at tip (flush every block) — and the non-empty rows are byte-identical across all three.

Two bugs this fixes on the way

1. Two save() calls on one Model instance in one block wedges master permanently. master's save() never sets exists, so the second call is another _insert():

error: conflicting key value violates exclusion constraint "votes_id__indexer_block_range_excl"
detail: Key (id, _indexer, block_range)=(v5, eth, [8,)) conflicts with existing key (v5, eth, [8,))
code: 23P01

...retried forever, indexer stuck. This branch coalesces it into a single version and produces v5 count=99 range=[8,). Nice catch.

2. master writes EMPTY-range junk rows. Any same-block create+delete, update+delete, or create+update makes _update/_delete close a range to int8range(N, N). In the 40-block workload master left 4 dead rows; this branch leaves 0.

Also _blocks is now an upsert instead of master's bare insert, which is the right call for replay. And the seenPoolTransactions move in the Starknet provider is correct and complete — EVM has no processPool, so there's no matching site to fix.

Dedup / upsert

Checked against real PG rather than assumed, since the two branches differ:

INSERT ... VALUES ('a','eth',1), ('a','eth',1) ON CONFLICT DO NOTHING;   -- INSERT 0 2, fine
INSERT ... VALUES ('a','eth',1), ('a','eth',9) ON CONFLICT DO UPDATE ...;
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time

Checkpoints use .ignore() so in-statement duplicates are safe; block hashes use .merge() and are collapsed through latestHashes first, which is exactly what's needed. Empty-buffer flush is a clean no-op — it returns before opening a transaction.

Throughput

It delivers. Same workload (one insert + one read-modify-write per block), 3000 blocks:

master   99.21s    30 blocks/sec
this PR   0.36s  8333 blocks/sec

and 20000 blocks including four real flushes still holds 1481 blocks/sec, ~50x.


Non-blocking comments inline. The one I'd most like you to look at is the read-path type drift on load().

Comment thread src/orm/entity-buffer.ts Resolved
Comment thread src/container.ts Resolved
Comment thread src/container.ts Resolved
Comment thread src/container.ts Resolved
Comment thread src/orm/entity-buffer.ts Resolved

@tony8713 tony8713 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at e72550e. Still an approve.

Resolved

  • entity-buffer.ts:112 read-path type drift — fixed, confirmed by measurement (all three states now return a true bigint, and += across a flush persists 1002 instead of corrupting). Details in the thread, plus one Float/Decimal note recorded there for later.
  • container.ts:40 shutdown drain — your call, agreed.

Still open. git diff 408e5c1 e72550e -- src/container.ts src/orm/ is empty, so these three are byte-identical to what I reviewed and stand as written:

  • container.ts:434 flush-error log — I overstated this and have corrected it in the thread. prepareFlush chunks at MAX_INSERT_ROWS = 1000, so it plateaus at a bounded ~60KB line, not the ~50k placeholders I claimed. The ask is now just the missing block context, not the volume.
  • container.ts:459 — re-measured on head. Same bufferSize=10002 in every run, heap at the cap set entirely by payload size: 14.3 / 43.6 / 102.2 / 199.9 MB for 1 / 4 / 10 / 20 KB entities. size getter: 4.9µs at 1k entities → 104µs at 10k → 516µs at 40k.
  • entity-buffer.ts:393 — flush() is still the only uncovered code in the file: 95.83 | 93.88 | 381-398, unchanged. It's also the only caller path that opens the transaction, and container.ts isn't imported by any test.

New — one inline comment below, on a stray NUL byte in entity-buffer.ts. Cosmetic in effect, but it makes the file invisible to grep, so it's worth the one-character fix.

Tests on head: 94 pass / 0 fail, tsc clean.

Comment thread src/orm/entity-buffer.ts Resolved

@bonustrack bonustrack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utACK

@Sekhmet
Sekhmet merged commit d26f8d1 into master Jul 31, 2026
1 check passed
@Sekhmet
Sekhmet deleted the sekhmet/buffered-writes branch July 31, 2026 20:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants